package com.flyco.modules.system.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.common.api.vo.Result;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.constant.CommonConstant;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.system.entity.*;
import com.flyco.modules.system.model.TreeModel;
import com.flyco.modules.system.service.*;
import com.flyco.modules.system.vo.DepartRolePermissionDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
* @Description: 门店角色
* @Author: jeecg-boot
* @Date:   2020-02-12
* @Version: V1.0
*/
@Slf4j
@Api(tags="门店角色")
@RestController
@RequestMapping("/f/sys/sysDepartRoleV2")
public class SysDepartRoleControllerV2 extends BaseController<SysDepartRole, ISysDepartRoleService> {
   @Autowired
   private ISysDepartRoleService sysDepartRoleService;

    @Autowired
    private ISysDepartRolePermissionService sysDepartRolePermissionService;

    @Autowired
    private ISysPermissionService sysPermissionService;


    /**
     * 分页列表查询
     *
     * @param sysDepartRole
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="门店角色-分页列表查询", notes="门店角色-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(SysDepartRole sysDepartRole,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SysDepartRole> queryWrapper = QueryGenerator.initQueryWrapper(sysDepartRole, req.getParameterMap());
        Page<SysDepartRole> page = new Page<>(pageNo, pageSize);
        IPage<SysDepartRole> pageList = sysDepartRoleService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    @ApiOperation(value="查询门店角色", notes="查询门店角色")
    @GetMapping(value = "/queryall")
    public Result<List<SysDepartRole>> list() {
        Result<List<SysDepartRole>> result = new Result<>();
        List<SysDepartRole> list = sysDepartRoleService.list();
        if(list==null||list.size()<=0) {
            result.error500("未找到角色信息");
        }else {
            result.setResult(list);
            result.setSuccess(true);
        }
        return result;
    }


    /**
    * 添加
    *
    * @param sysDepartRole
    * @return
    */
   @AutoLog(value = "门店角色-添加")
   @ApiOperation(value="门店角色-添加", notes="门店角色-添加")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody SysDepartRole sysDepartRole) {
       sysDepartRoleService.save(sysDepartRole);
       return Result.ok("添加成功！");
   }

   /**
    * 编辑
    *
    * @param sysDepartRole
    * @return
    */
   @AutoLog(value = "门店角色-编辑")
   @ApiOperation(value="门店角色-编辑", notes="门店角色-编辑")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody SysDepartRole sysDepartRole) {
       sysDepartRoleService.updateById(sysDepartRole);
       return Result.ok("编辑成功!");
   }

   /**
    * 通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "门店角色-通过id删除")
   @ApiOperation(value="门店角色-通过id删除", notes="门店角色-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       sysDepartRoleService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    * 批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "门店角色-批量删除")
   @ApiOperation(value="门店角色-批量删除", notes="门店角色-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.sysDepartRoleService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功！");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @ApiOperation(value="门店角色-通过id查询", notes="门店角色-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       SysDepartRole sysDepartRole = sysDepartRoleService.getById(id);
       return Result.ok(sysDepartRole);
   }

    /**
     * 用户角色授权功能，查询菜单权限树
     * @param request
     * @return
     */
    @ApiOperation(value="查询菜单权限树", notes="查询菜单权限树")
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<Map<String,Object>> queryTreeList(HttpServletRequest request) {
        Result<Map<String,Object>> result = new Result<>();
        //全部权限ids
        List<String> ids = new ArrayList<>();
        try {
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.orderByAsc(SysPermission::getSortNo);
            List<SysPermission> list = sysPermissionService.list(query);
            for(SysPermission sysPer : list) {
                ids.add(sysPer.getId());
            }
            List<TreeModel> treeList = new ArrayList<>();
            getTreeModelList(treeList, list, null);
            Map<String,Object> resMap = new HashMap<String,Object>();
            resMap.put("treeList", treeList); //全部树节点数据
            resMap.put("ids", ids);//全部树ids
            result.setResult(resMap);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    private void getTreeModelList(List<TreeModel> treeList,List<SysPermission> metaList,TreeModel temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getName(),permission.getRuleFlag(), permission.isLeaf());
            if(temp==null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if(!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }else if(temp!=null && tempPid!=null && tempPid.equals(temp.getKey())){
                temp.getChildren().add(tree);
                if(!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }

        }
    }

    /**
     * 保存角色授权
     */
    @ApiOperation(value="保存角色授权", notes="保存角色授权")
    @RequestMapping(value = "/saveRolePermission", method = RequestMethod.POST)
    public Result saveRolePermission(@RequestBody DepartRolePermissionDTO departRolePermissionDTO) {
        if(StrUtil.isBlank(departRolePermissionDTO.getRoleId()) || StrUtil.isBlank(departRolePermissionDTO.getPermissionIds())){
            return Result.error("参数不能为空");
        }

        List<SysDepartRolePermission> collect = Arrays.stream(departRolePermissionDTO.getPermissionIds().split(",")).map(permissionId -> {
            SysDepartRolePermission departRolePermission = new SysDepartRolePermission();
            departRolePermission.setRoleId(departRolePermissionDTO.getRoleId());
            departRolePermission.setPermissionId(permissionId);
            return departRolePermission;
        }).collect(Collectors.toList());

        sysDepartRolePermissionService.remove(Wrappers.lambdaQuery(SysDepartRolePermission.class).eq(SysDepartRolePermission::getRoleId,departRolePermissionDTO.getRoleId()));
        sysDepartRolePermissionService.saveBatch(collect);

        return Result.ok("保存成功");
    }

    /**
     * 查询角色授权
     */
    @ApiOperation(value="查询角色授权", notes="查询角色授权")
    @RequestMapping(value = "/queryRolePermission", method = RequestMethod.GET)
    public Result<List<String>> queryRolePermission(@RequestParam(name = "roleId", required = true) String roleId) {
        Result<List<String>> result = new Result<>();
        try {
            List<SysDepartRolePermission> list = sysDepartRolePermissionService.list(Wrappers.lambdaQuery(SysDepartRolePermission.class).eq(SysDepartRolePermission::getRoleId, roleId));
            result.setResult(list.stream().map(SysDepartRolePermission::getPermissionId).collect(Collectors.toList()));
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }





}
